package pkg_beans;

import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.context.RequestContext;
import pkg_entidades.Usuario;

@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean implements Serializable {

    private Usuario usuario;
    @EJB
    private pkg_sessionBeans.UsuarioFacadeLocal usEjbFacade;
    private String username;
    private String password;
    private String msjIngreso;
    private String msjRegistro;
    private boolean loggedIn;

    public LoginBean() {
        msjIngreso = "Ingresar";
        loggedIn = false;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMsjIngreso() {
        return msjIngreso;
    }

    public void setMsjIngreso(String msjIngreso) {
        this.msjIngreso = msjIngreso;
    }

    public String getMsjRegistro() {
        return msjRegistro;
    }

    public void setMsjRegistro(String msjRegistro) {
        this.msjRegistro = msjRegistro;
    }

    public void login() {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg;
        loggedIn = false;
        usuario = usEjbFacade.findBySeudonimo(username);

        if (usuario != null) {
            if (password != null && password.equals(usuario.getUsrPasswd())) {
                loggedIn = true;
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenido", username);
                msjIngreso = "Hola " + username;
            } else {
                msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Clave incorrecta");
            }
        } else {
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Nombre de usuario incorrecto");
        } 

        FacesContext.getCurrentInstance().addMessage(null, msg);
        context.addCallbackParam("loggedIn", loggedIn);
    }
}
